package com.frank.wiki.service;

import com.frank.wiki.domain.Ebook;
import com.frank.wiki.domain.EbookExample;
import com.frank.wiki.mapper.EbookMapper;
import com.frank.wiki.req.EbookQueryReq;
import com.frank.wiki.req.EbookSaveReq;
import com.frank.wiki.resp.EbookQueryResp;
import com.frank.wiki.resp.PageResp;
import com.frank.wiki.utils.CopyUtil;
import com.frank.wiki.utils.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {

    @Resource
    private EbookMapper ebookMapper;
    @Resource
    private SnowFlake snowFlake;

    public List<Ebook> getAll() {
        return ebookMapper.selectByExample(null);
    }

    public PageResp<EbookQueryResp> getEbook(EbookQueryReq ebookQueryReq) {
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();

        if (!ObjectUtils.isEmpty(ebookQueryReq.getName())) {
            criteria.andNameLike("%" + ebookQueryReq.getName() + "%");
        }
        if(!ObjectUtils.isEmpty(ebookQueryReq.getCategory2Id())){ // 根据二级分类查询内容,带条件
            criteria.andCategory2IdEqualTo(ebookQueryReq.getCategory2Id());
        }
        PageHelper.startPage(ebookQueryReq.getPage(), ebookQueryReq.getSize());// 1代码从第几页查，3代表每页显示3条数据.
        // 需要注意的是，这行代码只对遇到的第一个select查询有用，因此在使用时，想对那个select分页就写在它的上一行
        // 这里查出来的是Ebook，里面字段和表字段是一样的，但是我们返回出去的是响应封装类，因此要转化一下
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        List<EbookQueryResp> respList = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        PageInfo<Object> pageInfo = new PageInfo<>();
        PageResp pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);

        return pageResp;
    }
    /**
     * 更新和添加方法
     */
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            // 更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }

}

